//
//  AppDelegate.m
//  MoreFunTV
//
//  Created by admin on 14-10-21.
//  Copyright (c) 2014Âπ? admin. All rights reserved.
//

#import "AppDelegate.h"
#import "UIImageView+AFNetworking.h"
#import <MediaPlayer/MediaPlayer.h>

#ifdef DEBUG
#include <mach/mach.h>
#endif

@implementation AppDelegate

#ifdef DEBUG
BOOL memoryInfo(vm_statistics_data_t *vmStats) {
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)vmStats, &infoCount);
    
    return kernReturn == KERN_SUCCESS;
}

- (void)logMemoryInfo {
    vm_statistics_data_t vmStats;
    
    if (memoryInfo(&vmStats)) {
        
        self.memoryLabel.text = [NSString stringWithFormat:@"free:%uM,use:%uM"
                                 ,vmStats.free_count * vm_page_size / 1024 / 1024,
                                 vmStats.active_count * vm_page_size / 1024 / 1024];
    }
}
#endif

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //iOS 将Log日志重定向输出到文件中保存
    
    // 当真机连接Mac调试的时候把这些注释掉，否则log只会输入到文件中，而不能从xcode的监视器中看到。
    // 如果是真机就保存到Document目录下的drmXXX.log文件中
//    UIDevice *device = [UIDevice currentDevice];
//    if (![[device model] isEqualToString:@"iPad Simulator"]) {
//        // 开始保存日志文件
//        [self redirectNSlogToDocumentFolder];
//    }
    
    //初始化应用语言
    [JAInternationalControl initUserLanguage];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //检测投射设备
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    // Hook up the logger.
    [MSFKLogger sharedInstance].delegate = self;
    // Initialize the matchstick device controller.
    self.matchstickDeviceController = [[MatchstickDeviceController alloc] init];
    [self.matchstickDeviceController selectingDevice];
    // Scan for devices.
    [self.matchstickDeviceController performScan:YES];

    
    // 监测网络情况
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(reachabilityChanged:) name: @"NetworkReachabilityChangedNotification" object: nil];
    self.hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [self.hostReach startNotifier];
    
    //自定义缓存
    self.myCache = [[ASIDownloadCache alloc] init];
    //设置缓存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    [self.myCache setStoragePath:[documentDirectory stringByAppendingPathComponent:@"MoreFunResource"]];
    [self.myCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
    
    //获取通知中心
    NSNotificationCenter *notificationDevice = [NSNotificationCenter defaultCenter];
    //添加通知到中心
    [notificationDevice addObserver:self selector:@selector(deviece:) name:@"myDevice" object:nil];
    
    //创建数据库
    [DBDaoHelper createAllTable];
    //创建tabar
    [self addTabar];
    
    //浮动的按钮
    self.avatar = [[RCDraggableButton alloc] initInKeyWindowWithFrame:CGRectMake(kScreenWidth-50, kScreenHeight-50-49, 50, 50)];
    [self.avatar setBackgroundImage:[UIImage imageNamed:@"shadow7bbb.png"] forState:UIControlStateNormal];
    self.avatar.backgroundColor = [UIColor colorWithRed:0.101 green:0.508 blue:1.000 alpha:0.900];
    [self.avatar setHidden:YES];
    //禁止拖来拖去
    [self.avatar setDraggable:NO];
    [self.avatar setTapBlock:^(RCDraggableButton *avatar) {
        //浮动的按钮发送通知
        [avatar setHidden:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myUIButton" object:nil userInfo:nil];
    }];
    [self.avatar setDragDoneBlock:^(RCDraggableButton *avatar) {//拖动停止后调用 将不走点击方法
    }];
    [self.avatar setAutoDockingBlock:^(RCDraggableButton *avatar) {
    }];
    [self.avatar setAutoDockingDoneBlock:^(RCDraggableButton *avatar) {
    }];
    
    //获取通知中心浮动按钮显示与否的方法
    NSNotificationCenter *notificationMyUIButton = [NSNotificationCenter defaultCenter];
    //添加通知到中心
    [notificationMyUIButton addObserver:self selector:@selector(myUIButtonSetHidden:) name:@"BtnSetHidden" object:nil];
    
//    //获取系统版本号 应用名  应用版本
//    float banBen = [AppDelegate getIOSVersion];
//    NSLog(@"系统版本号----------%f",banBen);
//    //获取UUID
//    [self uuid];
//    NSLog(@"UUID为%@",[self uuid]);
    
#ifdef DEBUG
    //debug时用来检测内存使用情况
    self.memoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 320, 25)];
    self.memoryLabel.backgroundColor = [UIColor greenColor];
    self.memoryLabel.alpha = 0.5;
    self.memoryLabel.textAlignment = NSTextAlignmentCenter;
    [self.window addSubview:self.memoryLabel];
    
    [NSTimer scheduledTimerWithTimeInterval:1. target:self selector:@selector(logMemoryInfo) userInfo:nil repeats:YES];
#endif
    
    return YES;
}

//创建tabar
-(void)addTabar
{
    HomeViewController *homeVc = [[HomeViewController alloc]init];
    UITabBarItem *itemHome = [[UITabBarItem alloc]initWithTitle:MyLocalizedString(@"tuijian") image:[UIImage imageNamed:@"hot1.png"] selectedImage:[UIImage imageNamed:@"hot2.png"]];
    homeVc.tabBarItem = itemHome;
    
    ClassViewController *classVc = [[ClassViewController alloc]init];
    UITabBarItem *itemClass = [[UITabBarItem alloc]initWithTitle:MyLocalizedString(@"fenlei") image:[UIImage imageNamed:@"fl1.png"] selectedImage:[UIImage imageNamed:@"fl2.png"]];
    classVc.tabBarItem = itemClass;
    
    SearchViewController *searchVc = [[SearchViewController alloc]init];
    UITabBarItem *itemSearch = [[UITabBarItem alloc]initWithTitle:MyLocalizedString(@"sousuo") image:[UIImage imageNamed:@"s1.png"] selectedImage:[UIImage imageNamed:@"s2.png"]];
    searchVc.tabBarItem = itemSearch;
    
    PersonalViewController *personalVc = [[PersonalViewController alloc]init];
    UITabBarItem *itemPersonal = [[UITabBarItem alloc]initWithTitle:MyLocalizedString(@"yonghu") image:[UIImage imageNamed:@"m1.png"] selectedImage:[UIImage imageNamed:@"m2.png"]];
    personalVc.tabBarItem = itemPersonal;
    
    NSArray *arrVc = [[NSArray alloc]initWithObjects:homeVc,classVc,searchVc,personalVc,nil];
    UITabBarController *tabBar = [[UITabBarController alloc]init];
    tabBar.viewControllers = arrVc;
    [tabBar.tabBar setBackgroundColor:[UIColor colorWithRed:243.0/255.0 green:243.0/255.0 blue:243.0/255.0 alpha:1.000]];
    
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:tabBar];
    [nav.navigationBar setBarTintColor:[UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.000]];
    self.window.rootViewController = nav;
}

//通知事件
-(void)deviece:(NSNotification *)notification
{
    SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
    if (_matchstickDeviceController.isConnected == NO) {//未连接状态
        setUp.isisConnected = NO;
        setUp.arrSheet = [[NSMutableArray alloc]init];
        for (int i = 0; i < _matchstickDeviceController.deviceScanner.devices.count; i++) {
            MSFKDevice *device = [_matchstickDeviceController.deviceScanner.devices objectAtIndex:i];
            // only show LAN IP.
            if (device.ipAddress == nil
                || [device.ipAddress isEqualToString:@"192.168.1.1"]
                || !([device.ipAddress hasPrefix:@"192"]
                     || [device.ipAddress hasPrefix:@"172"]
                     || [device.ipAddress hasPrefix:@"10"])) {
                    //过滤掉的设备
                }
            else {
                [setUp.arrSheet addObject:device.friendlyName];
            }
        }
    }else{//已连接状态
        int count = 0;
        setUp.isisConnected = YES;
        for (int i = 0; i < setUp.arrSheet.count; i++) {
            NSString *strDevice = [setUp.arrSheet objectAtIndex:i];
            if ([strDevice isEqual:MyLocalizedString(@"delegate1")]) {
                count++;
            }
        }
        
        if (count == 0) {
            [setUp.arrSheet addObject:MyLocalizedString(@"delegate1")];
        }
    }
    
    NSString *srtTitle = MyLocalizedString(@"delegate2");
    NSString *srtMessage = @"      ";
    if (self.matchstickDeviceController.isConnected == NO) {//未连接状态
    }else{
        srtTitle = MyLocalizedString(@"delegate3");
        srtMessage = @"      ";
    }
    
    JGActionSheetSection *sheetBtn = [JGActionSheetSection sectionWithTitle:srtTitle message:srtMessage buttonTitles:setUp.arrSheet buttonStyle:JGActionSheetButtonStyleDefault];
    JGActionSheet *sheet = [JGActionSheet actionSheetWithSections:@[sheetBtn]];
    sheet.delegate = self;
    
    sheet.insets = UIEdgeInsetsMake(20, 0.0f, 220, 0.0f);
    [sheet showInView:self.window animated:YES];
    
    [sheet setButtonPressedBlock:^(JGActionSheet *sheet, NSIndexPath *indexPath) {
        [sheet dismissAnimated:YES];
    }];
}

// 将NSlog打印信息保存到Document目录下的文件中
- (void)redirectNSlogToDocumentFolder
{
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    // 注意不是NSData!
    NSString *fileName = [NSString stringWithFormat:@"dr_%@.log",currentDateStr];
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
    // 先删除已经存在的文件
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    [defaultManager removeItemAtPath:logFilePath error:nil];
    
    // 将log输入到文件
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
    
    //输出格式为：2010-10-27 10:22:13
    NSLog(@"___currentDateStr:%@",currentDateStr);
}

- (void)actionSheet:(JGActionSheet *)actionSheet pressedButtonAtIndexPath:(NSIndexPath *)indexPath
{
    _setuuuuP = [SetUpSingleton sharedSetUp];
    //未连接状态
    if (self.matchstickDeviceController.isConnected == NO) {
        NSMutableArray *deviceArr = [[NSMutableArray alloc] init];
        for (int i = 0; i < _matchstickDeviceController.deviceScanner.devices.count; i++) {
            MSFKDevice *device = [_matchstickDeviceController.deviceScanner.devices objectAtIndex:i];
            // only show LAN IP.
            if (device.ipAddress == nil
                || [device.ipAddress isEqualToString:@"192.168.1.1"]
                || !([device.ipAddress hasPrefix:@"192"]
                     || [device.ipAddress hasPrefix:@"172"]
                     || [device.ipAddress hasPrefix:@"10"])) {
                    //过滤掉的设备
                }
            else {
                [deviceArr addObject:device];
            }
        }
        MSFKDevice *device = [deviceArr objectAtIndex:indexPath.row];
        NSLog(@"Selecting device1:%@", device.friendlyName);
        [[NSNotificationCenter defaultCenter] postNotificationName:@"selectingDevice" object:nil userInfo:nil];
        
        [self.matchstickDeviceController connectToDevice:device];
        
        NSString *str = [_setuuuuP.arrSheet objectAtIndex:[indexPath row]];
        [_setuuuuP.arrSheet removeAllObjects];
        [_setuuuuP.arrSheet addObject:str];
    }
    else{//已连接状态
        if ([indexPath row] == 0) {
            [_setuuuuP.arrSheet removeLastObject];
        }
        else{//断开连接
            [DBDaoHelper deleteAllTouShe];
            _setuuuuP.count = 0;
            _setuuuuP.arrCount = 0;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:nil userInfo:nil];
            [self.matchstickDeviceController stopFlingMedia];
            [self.matchstickDeviceController stopApplication];
            [self.matchstickDeviceController disconnectFromDevice];
            [_setuuuuP.arrSheet removeAllObjects];
        }
    }
}

//按钮显示与否的方法
-(void)myUIButtonSetHidden:(NSNotification *)notification{
    SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
    if ([setUp.strHidden isEqual:@"NO"]) {
        [self.avatar setHidden:NO];
    }
    else{
        [self.avatar setHidden:YES];
    }
}

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    id presentedViewController = [window.rootViewController presentedViewController];
    NSString *className = presentedViewController ? NSStringFromClass([presentedViewController class]) : nil;
    if (window && ([className isEqualToString:@"MPMoviePlayerViewController"] || [className isEqualToString:@"AVFullScreenViewController"]))
    {
        return UIInterfaceOrientationMaskAll;
    }
    else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    //删除所有直播EPG信息
    [DBDaoHelper deleteAllEPG];
    
    //标记变换
    SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
    setUp.firstWeiShiEpg = YES;
    setUp.firstDiFangEPG = YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    //删除所有直播ID信息和EPG信息
    [DBDaoHelper deleteAllLiveID];
    [DBDaoHelper deleteAllEPG];
    
    //标记变换
    SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
    setUp.firstWeiShiID = YES;
    setUp.firstDiFangID = YES;
    setUp.firstWeiShiEpg = YES;
    setUp.firstDiFangEPG = YES;
}

- (void)logFromFunction:(const char *)function message:(NSString *)message {
    // Send SDK’s log messages directly to the console, as an example.
    NSLog(@"。。。。。。。。。%s  %@", function, message);
}

//监测网络连接的事件
- (void)reachabilityChanged:(NSNotification *)note {
    self.hostReach = [note object];
    NSParameterAssert([self.hostReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [self.hostReach currentReachabilityStatus];
    
    NSString *pStr_NO = MyLocalizedString(@"delegate4");
    NSString *pStr_3G = MyLocalizedString(@"delegate5");
    
    if (status == NotReachable){//无网络连接
        [self alertShow:pStr_NO];
    }
    else if (status == ReachableViaWiFi){//WiFi连接
    }
    else if (status == ReachableViaWWAN){//2G/3G/4G网络
        SetUpSingleton *setUp = [SetUpSingleton sharedSetUp];
        if ([setUp.strNetFlag isEqual:@"YES"]) {
            [self alertShow:pStr_3G];
        }
    }
}

//弹出提示框
-(void)alertShow:(NSString *)str
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:str delegate:self cancelButtonTitle:MyLocalizedString(@"cancel") otherButtonTitles:MyLocalizedString(@"delegate6"), nil];
    [alert show];
}

////获取系统版本号 应用名 应用版本号
//+ (float)getIOSVersion
//{
//    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
//    NSString *versionNum =[infoDict objectForKey:@"CFBundleVersion"];
//    NSString *appName =[infoDict objectForKey:@"CFBundleDisplayName"];
//    NSString *text =[NSString stringWithFormat:@"%@ ---%@",appName,versionNum];
//    NSLog(@"应用名称和版本号：%@",text);
//    return [[[UIDevice currentDevice] systemVersion] floatValue];
//}
//
////获取UUID
//-(NSString*) uuid {
//    CFUUIDRef puuid = CFUUIDCreate( nil );
//    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
//    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
//    CFRelease(puuid);
//    CFRelease(uuidString);
//    return result;
//}

@end
